/*
 * Copyright 2022-2027 中国信息通信研究院云计算与大数据研究所
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 
package com.controller;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.constant.ClusterConstant;
import com.common.context.SpringContextUtils;
import com.common.fastjson.JsonResult;
import com.localMapper.ClustercfgMapper;
import com.pojo.Clustercfg;
import com.service.impl.DataRecoveryServiceImpl;
import com.service.impl.InitialDataServiceImpl;

@RestController
public class InitialDataController {

    private final Logger logger = LoggerFactory.getLogger(InitialDataController.class); 

    @Autowired
	private RestTemplate restTemplate;
    @Autowired
    private ClustercfgMapper clustercfgMapper;
    
    @RequestMapping("/begin")
    public JsonResult begin(@Param(value = "datacfg_id")String datacfg_id) {
    	try {
    		List<Clustercfg> clusterList = clustercfgMapper.getClustercfg();
            for(Clustercfg clustercfg:clusterList) {
            	if(ClusterConstant.CLUSTER_MASTER.equals(clustercfg.getCluster_type())) {
                	String process_id = UUID.randomUUID().toString().replace("-", "");
            		JSONObject json = new JSONObject();
            		json.put("datacfg_id", datacfg_id);
            		json.put("process_id", process_id);
            		HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                    HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(JSON.parseObject(json.toJSONString()), headers);
                	logger.info(" InitialDataController begin init {} ",json.toJSONString());
                    HttpEntity<String> resultObj = restTemplate.exchange(clustercfg.getCluster_url()+"init", HttpMethod.POST, entity, String.class);
            		JsonResult jsonResult = JSON.parseObject(resultObj.getBody(), JsonResult.class);
                	logger.info(" InitialDataController begin init result {} ",jsonResult.toString());
                	jsonResult.setData(process_id);
            		return jsonResult;
            	}
            }
		} catch (Exception e) {
        	logger.error(" InitialDataController begin is error {} ",e);
		}
		return JsonResult.failure(" cluster master is not exist ");
    }
    
    @RequestMapping(value = {"/init"}, method = RequestMethod.POST)
    public JsonResult init(@RequestBody Map<String, String> param){
    	String datacfg_id = param.get("datacfg_id");
    	String process_id = param.get("process_id");
    	logger.info(" InitialDataController begin datacfg_id {} process_id {} ",datacfg_id,process_id);
    	InitialDataServiceImpl initialDataServiceImpl = SpringContextUtils.getBean(InitialDataServiceImpl.class);
    	initialDataServiceImpl.setDatacfg_id(datacfg_id);
    	initialDataServiceImpl.setProcess_id(process_id);
    	Thread thread = new Thread(initialDataServiceImpl); 
    	thread.start();
    	logger.info(" InitialDataController end datacfg_id {} process_id {} ",datacfg_id,process_id);
    	return JsonResult.success();
    }
    
    @RequestMapping("/datarecovery")
    public JsonResult datarecovery() {
    	DataRecoveryServiceImpl dataRecoveryServiceImpl = SpringContextUtils.getBean(DataRecoveryServiceImpl.class);
    	Thread thread = new Thread(dataRecoveryServiceImpl); 
    	thread.start();
    	return JsonResult.success();
    }
}
